# Given an array of integers, return indices of the two numbers such that they add up to a specific target.

# You may assume that each input would have exactly one solution.

# Example:
# Given nums = [2, 7, 11, 15], target = 9
# Because nums[0] + nums[1] = 2 + 7 = 9
# return [0, 1]

#O(n^2)/O(1)
#遍历所有组合
class Solution_1(object):
    def twoSum(self, nums, target):
        count =  len(nums)

        for i in range(0, count):
            for j in range(i+1, count):
                if nums[i] + nums[j] == target:
                    return [i, j]

#O(n)/O(n)
class Solution_2(object):
    def twoSum(self, nums, target):
        values = dict() #[值，键]缓存

        for index, value in enumerate(nums): #遍历字典
            complement = target - value #当前值需要配对的值
            if(complement in values): #查找缓存值
                return [values[complement], index] #返回配对值的键和当前键

            values[value] = index #如果缓存不存在配对值，记录当前[键，值]为[值，键]到缓存

#test
solution = Solution_2()
result = solution.twoSum([2, 7, 11, 15], 9)
print("\n", "-----------------------------------------------------", "\n")
print(result)
print("\n", "-----------------------------------------------------", "\n")